package jstart.exe;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author zwz
 * Created on 2021-02-08
 */
public class AppClassLoader extends URLClassLoader {

    static {
        registerAsParallelCapable();
    }

    public AppClassLoader(ClassLoader parent) {
        super(new URL[0], parent);
    }

    void addFileOrDir(File fileOrDir) {
        if (fileOrDir == null || !fileOrDir.exists()) return;
        try {
            if (fileOrDir.isFile()) {
                addFile(fileOrDir);
            } else {
                addDir(fileOrDir);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    void addFile(File file) throws MalformedURLException {
        addURL(file.toURI()
                   .toURL());
    }

    void addDir(File dir) throws MalformedURLException {
        File[] jarFiles = dir.listFiles(
                file -> file.isFile() && file.getName()
                                             .toLowerCase()
                                             .endsWith(".jar"));
        if (jarFiles == null || jarFiles.length == 0) return;

        for (File jar : jarFiles) {
            addFile(jar);
        }
    }
}
